package com.wocai.jrt.orgadmin.message.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wocai.jrt.orgadmin.message.model.MessageLog;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.utils.MessagePush;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;

/**
 * 消息日志控制器
 * @author zhangyz
 * @date 2015-8-19 16:27:42
 */
@Controller
@RequestMapping("/message")
public class MessageLogAction extends GenericAction<MessageLog> {
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogAction.class);
	
	@Inject
	private MessageLogService messageLogServiceImpl;
	
	/**
     * 获得消息日志List，初始化列表页。
     * @param model 参数
     * @return 消息日志List
     */
    @RequestMapping("/list")
    public String list(MessageLog model, Map<String, Object> maps) {
    	try {
    		List<MessageLog> list = messageLogServiceImpl.pagedList(model);
            maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "message/list";
    }
	
	/**
	 * 获得消息日志List，Json格式。
	 * @param model 参数
	 * @return 消息日志List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody MessageLog model) {
		Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		Date date = model.getEndTime();
    		if (date!=null) {
    			model.setEndTime(new DateTime(date).plusHours(23).plusMinutes(59).plusSeconds(59).toDate());
			}
    		//获取当前机构ID
		    model.setOrgId(UserUtils.getOrgId());
		    //model.setEmployeeId(UserUtils.getUserId());
		    model.setOrderBy("create_time desc");
    		List<MessageLog> list = messageLogServiceImpl.queryMyList(model);
    		// 统计的时候，不需要分页
    		model.setPage(null);
    		long totalRecord  = messageLogServiceImpl.queryMyList(model).size();
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("message query success.");
    		}
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("message query error, msg=[{}]", e.getMessage());
		}
        return result;
	}
	
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody MessageLog model) {
    	JsonBean bean = new JsonBean();
    	String orgString = UserUtils.getOrgId();
    	model.setId(ObjectId.get().toString());
    	model.setCreateTime(new Date());
    	//当前用户作为通知发送人
    	model.setSender(UserUtils.getOrgId());
    	//设置消息发送机构
    	model.setOrgId(orgString);
    	if (model.getType()==null) {
    		 bean.setCode(0);
             bean.setMessage("发送对象参数不能为空");
             return bean;
		}
    	if (StringUtils.isBlank(model.getMessage())) {
    		bean.setCode(0);
            bean.setMessage("发送的消息不能为空");
            return bean;
		}
    	try {
    		/*	//将通知存入消息表中
    		int msgs = messageLogServiceImpl.saveMessage(model);
    		 if (msgs != 1){
                 bean.setCode(0);
                 bean.setMessage("消息添加失败");
                 return bean;
             }*/
    		//获取机构下所有员工列表
 			List<String> employeeList = messageLogServiceImpl.getEmployeeList(model.getOrgId());
 			//该机构下没有员工
 			if (employeeList.size() == 0) {
 				    bean.setMessage("该机构下暂时没有员工");
					return bean;
				}
 			//将消息存入messag_log表中
 			List<MessageLog> msgLogList = new ArrayList<MessageLog>();
 			for (String str : employeeList) {
 				MessageLog msgLog = new MessageLog();
 				Date date = new Date();
 				msgLog.setCreateTime(date);
 				msgLog.setSender(UserUtils.getUserId());
 				msgLog.setSource("机构后台");
 				msgLog.setSendTime(date);
 				msgLog.setMessage("通知:"+model.getMessage());
 				msgLog.setMessageType(1);
 				msgLog.setOrgId(model.getOrgId());
 				msgLog.setType(model.getType());
 				msgLog.setState(0);
 				msgLog.setId(ObjectId.get().toString());
 				msgLog.setEmployeeId(str);
 				msgLogList.add(msgLog);
				}
 			int i = messageLogServiceImpl.msgLogInsertBatch(msgLogList);
 			bean.setData(i);
            int size = msgLogList.size();
            if (size == i  ) {
				bean.setCode(1);
                bean.setMessage("消息日志添加成功");
                LOGGER.info("消息日志添加成功");
			}else if (size < i && i != 0) {
				bean.setCode(1);
                bean.setMessage("部分消息日志添加成功");
                LOGGER.info("部分消息日志添加成功");
			}else{
				bean.setCode(0);
                bean.setMessage("消息日志添加失败");
                LOGGER.info("消息日志添加失败");
			}
            return bean;
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("消息日志添加失败");
			return bean;
		} finally{
			 //1机构PC后台(只需要向机构后台发送消息)
            if (model.getType() == 1) {
            	
            //2机构PAD(需要向机构所有员工发送消息)
    		}else if(model.getType() == 2){
    			//向机构所有员工pad端发送消息
    			MessagePush messagePush = new MessagePush(model.getMessage(),"机构消息");
    			messagePush.sendPushTag(model.getOrgId());
    		}
        }
    }
    
    /**
     * 查看消息详情。
     * @param model 查询参数，携带ID
     * @return JsonBean
     */
    @ResponseBody
    @RequestMapping("/detail")
    public JsonBean detail(@RequestBody MessageLog model) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(model.getId())) {
    		bean.setCode(0);
			bean.setMessage("参数错误");
			return bean;
		}
    	try {
    		model = messageLogServiceImpl.get(model.getId());
    		bean.setCode(1);
    		bean.setData(model);
    		bean.setMessage("参数错误");
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			bean.setCode(0);
			bean.setMessage("查询消息错误"+e.getMessage());
		}
        return bean;
    }
 
}
